#include <Board.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

Board::Board () {
	for (int i = 0; i < 8; ++i)
		for (int j = 0; j < 8; ++j)
			if (j < 2) mBoard[i][j].p = '1';
			else if (j < 6) mBoard[i][j].p = ' ';
			else mBoard[i][j].p = '2';
	mBoard[0][0].c = 'R';
	mBoard[1][0].c = 'J';
	mBoard[2][0].c = 'B';
	mBoard[3][0].c = 'Q';
	mBoard[4][0].c = 'K';
	mBoard[5][0].c = 'B';
	mBoard[6][0].c = 'J';
	mBoard[7][0].c = 'R';
	for (int i = 0; i < 8; ++i) mBoard[i][1].c = 'P';
	for (int i = 0; i < 8; ++i)
		for (int j = 2; j <= 5; ++j) mBoard [i][j].c = ' ';
	mBoard[0][7].c = 'R';
	mBoard[1][7].c = 'J';
	mBoard[2][7].c = 'B';
	mBoard[3][7].c = 'Q';
	mBoard[4][7].c = 'K';
	mBoard[5][7].c = 'B';
	mBoard[6][7].c = 'J';
	mBoard[7][7].c = 'R';
	for (int i = 0; i < 8; ++i) mBoard[i][6].c = 'P';
	
}

void Board::print () {
	for (int i = 7; i >= 0; --i) {
		cout << i+1 << ' ';
		for (int j = 7; j >= 0; --j)
			cout << mBoard [j][i].c << mBoard [j][i].p << ' ';
		cout << endl;
	}
	cout << "   A  B  C  D  E  F  G  H" << endl;
}

bool Board::move (Point p1, Point p2, char p) {

	if ((p2.x >= 8 && p2.y >= 8) || mBoard[p1.x][p1.y].p != p) return false;
	if ( p1.x == p2.x && p1.y == p2.y) return false;

	char pawn = mBoard [p1.x][p1.y].c;
	switch (pawn) {
	case 'K': if (abs(p2.x-p1.x)+abs(p2.y-p1.y) == 1) break;
		return false;
	case 'Q': break;
		return false;
	case 'R': if (p1.x == p2.x)
			for (int i = p1.y; i == p2.y; ++i)
				if (mBoard[p1.x][i].c != ' ') return false;
		if (p1.y == p2.y)
			for (int i = p1.x; i == p2.x; ++i)
				if (mBoard[i][p1.y].c != ' ') return false;
		break;
	case 'B': if (abs (p1.x-p2.x) == abs (p1.y-p2.y)) break;
 		//if there is pawns from p1->p2
		return false;
	case 'J': if ((abs (p1.x-p2.x) == 1 && abs (p2.y-p2.y) == 2)
		|| (abs (p1.x-p2.x) == 2 || abs (p1.y-p2.y == 1))) break;
		return false;
	case 'P': 
		if (p1.x == p2.x && p2.y-p1.y == 1)		// player 1
			if (mBoard [p2.x][p2.y].c == ' ') break;
		if (p1.x == p2.x && p2.y-p1.y == 2 && p == 1 && p1.y == 1)
			if (mBoard [p2.x][p2.y].c == ' ') break;
		if (abs (p1.x-p2.x) == 1 && p2.y-p1.y == 1)
			if (mBoard [p2.x][p2.y].p != 0 && mBoard [p2.x][p2.y].p != p)
				break;
		if (p1.x == p2.x && p2.y-p1.y == -1)		// player 2
			if (mBoard [p2.x][p2.y].c == ' ') break;
		if (p1.x == p2.x && p2.y-p1.y == -2 && p == 1 && p1.y == 6)
			if (mBoard [p2.x][p2.y].c == ' ') break;
		if (abs (p1.x-p2.x) == 1 && p2.y-p1.y == -1)
			if (mBoard [p2.x][p2.y].p != 0 && mBoard [p2.x][p2.y].p != p)
				break;
		return false;
	}

	mBoard[p1.x][p1.y] = mBoard[p2.x][p2.y];
	mBoard [p2.x][p2.y].c = mBoard [p1.x][p1.y].c;
	mBoard [p2.x][p2.y].p =  p; 
	mBoard [p1.x][p1.y].c = ' '; mBoard [p1.x][p1.y].p = '0';
	return true;
}
